package com.cmw.socket.l7.client;

import com.cmw.socket.bean.ServerInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Socket 客户端
 * @author chengmingwei
 * @date 2020-06-27 20:27
 */
@Slf4j
public class Client {

    public static void main(String[] args){
        ServerInfo serverInfo = UDPSearcher.searchServer(10000);
        log.info("Server:{}", serverInfo);
        if(null == serverInfo){
            log.error("服务器配置信息 serverInfo 为空!");
            return;
        }
        TCPClient tcpClient = null;
        try {
            tcpClient = TCPClient.startWith(serverInfo);
            if(null == tcpClient){
                log.error("TCPClient 对象为空!");
                return;
            }
            write(tcpClient);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void write(TCPClient tcpClient) throws IOException {
        //构建键盘输入流
        InputStream in = System.in;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
        do{
            // 键盘读取一行
            String str = bufferedReader.readLine();
            //发送到服务器
            tcpClient.send(str);
            if("00bye00".equalsIgnoreCase(str)) break;
        }while (true);
    }
}
